<?php
include('include/config.inc.php');
if(!isset($_SESSION['s_activId'.$cfgPack])
  || (isset($_SESSION['s_userType'.$cfgPack]) && isset($cfgFileNames['dailyreportmaster'][$_SESSION['s_userType'.$cfgPack]]) 
      && $cfgFileNames['dailyreportmaster'][$_SESSION['s_userType'.$cfgPack]] == 0))
{
  $_SESSION['s_urlRedirectDir'] = $_SERVER['REQUEST_URI'];
  header("Location:checkLogin.php");
}
else
{
  $deliveryChallanArray    = array();
  $deliveryDetailArray     = array();
  $deliveryChallanCount    = 0;
  $pendingDCCount          = 0;
  $masterDeliveryId        = isset($_REQUEST['masterDeliveryId']) ? $_REQUEST['masterDeliveryId'] :0;
  $deliveryChallanMasterId = isset($_REQUEST['deliveryChallanMasterId']) ? $_REQUEST['deliveryChallanMasterId'] :0;
  
  /////////////////  Final Master Date : Start

  if(isset($_POST['proformaSubmit']) && $_POST['proformaSubmit'] > 0)
  {
    $deliveryChallanMasterId = isset($_POST['deliveryChallanMasterId']) ? $_POST['deliveryChallanMasterId'] : 0;
    $date                    = date("Y-m-d");
    $totalAmt                = isset($_POST['totAmount']) ? $_POST['totAmount']: 0;
    $notes                   = isset($_POST['notes'])  ? $_POST['notes']: "";
    $itemText                = isset($_POST['itemText'])  ? $_POST['itemText']: "";
   	
   	$insertPerfoma = "INSERT INTO proformamaster (deliveryChallanMasterId,date,totalAmt,notes)
    	                         VALUES ('".$deliveryChallanMasterId[0]."','".$date."',".$totalAmt.",'".nl2br(addslashes($notes))."')";
    $insertPerfoma = mysql_query($insertPerfoma);
    if(!$insertPerfoma)
    {
      die("Insert Query Not Inserted in Master Table : ".mysql_error());
    }
    else
    {
    	$proformaMasterId = mysql_insert_id();
      foreach($_POST['unitAmount'] as $deatilcnt => $deatilvalue)
      {
      	if($deatilvalue != "" || $deatilvalue != 0)
      	{
      		//echo $deatilvalue;
        	$deliveryChallanMasterId = ($_POST['deliveryChallanMasterId'][$deatilcnt] != '' ) ?  $_POST['deliveryChallanMasterId'][$deatilcnt] : 0;
        	$itemId                  = ($_POST['itemId'][$deatilcnt] != '' ) ?  $_POST['itemId'][$deatilcnt] : 0;
        	$qty                     = ($_POST['quantity'][$deatilcnt] != '' ) ?  $_POST['quantity'][$deatilcnt] : 0;
        	$unitRate                = ($_POST['unitRate'][$deatilcnt] != '' ) ?  $_POST['unitRate'][$deatilcnt] : 0;
        	
          $insertPerfomaDeatil = "INSERT INTO proformadetail (proformaMasterId,masterDeliveryId,deliveryChallanDetailId,itemId,qty,unitRate,amount,deliveryChallanMasterId)
                                  VALUES (".$proformaMasterId.",".$_POST['masterDeliveryId'].",".$deatilcnt.",".$itemId.",".$qty.",".$unitRate.",".$deatilvalue.",".$deliveryChallanMasterId.")";
          $insertPerfomaDeatilRes = mysql_query($insertPerfomaDeatil);
          if(!$insertPerfomaDeatilRes)
          {
          	 die("INSERT QUERY NOT INSERTED : ".mysql_error());
          }
          else
          {
          	$updateDelChallan = "UPDATE deliverychallandetail
          	                        SET isProforCreated = 'Y'
          	                      WHERE deliveryChallanDetailId =".$deatilcnt;
            $updateDelChallanRes = mysql_query($updateDelChallan);
          	$updateMasterDel = "UPDATE masterdelivery
          	                        SET isProforCreated = 'Y'
          	                      WHERE masterDeliveryId =".$_POST['masterDeliveryId'];
            $updateMasterDelRes = mysql_query($updateMasterDel);
          }
      	}
      }
    	foreach ($_POST['textName'] as $textkey => $textvalue)
    	{
    		$itemText  = ($_POST['textName'][$textkey] != '' ) ?  $_POST['textName'][$textkey] : "";
      	$textAmt   = ($_POST['textAmount'][$textkey] != '' ) ?  $_POST['textAmount'][$textkey] : 0;
      	
        $insertItem = "INSERT INTO proformadetail(proformaMasterId,masterDeliveryId,deliveryChallanDetailId,itemText,textAmt)
      	                  VALUES (".$proformaMasterId.",".$_POST['masterDeliveryId'].",".$deatilcnt.",'".nl2br(addslashes($itemText))."',".$textAmt.")";
        $insertQuery = mysql_query($insertItem);
      }
    }
    header("Location:proformaList.php");
  }
  // Selection of data when final master created : Starts
  
	$selFinalMaster = "SELECT *,DATE_FORMAT(dateMaster,'%d-%m-%Y') AS fmDate 
	                     FROM masterdelivery 
	                    WHERE masterDeliveryId =".$masterDeliveryId;
  $selFMRes = mysql_query($selFinalMaster);
  while($fmRow = mysql_fetch_array($selFMRes))
  {
  	$deliveryChallanArray[$deliveryChallanCount]['masterDeliveryId']  = $fmRow['masterDeliveryId'];
  	$deliveryChallanArray[$deliveryChallanCount]['fmDate']            = $fmRow['fmDate'];
  	
  	$selMstDtl = "SELECT deliverychallandetail.deliveryChallanDetailId,deliverychallandetail.discription, deliverychallandetail.quantity,deliverychallanmaster.srNo,
  	                     DATE_FORMAT(deliverychallanmaster.delivaryDate,'%d-%m-%Y') AS delivaryDate,deliverychallanmaster.challanType,
  	                     deliverychallanmaster.deliveryChallanMasterId,party.companyName,item.itemId,item.itemName,subcategory.subCategoryName,
  	                     deliverychallanmaster.deliveryChallanMasterId
  	                FROM deliverychallandetail
  	                JOIN deliverychallanmaster ON deliverychallandetail.deliveryChallanMasterId = deliverychallanmaster.deliveryChallanMasterId
  	                JOIN party ON deliverychallanmaster.partyId = party.partyId
  	                JOIN item ON item.itemId = deliverychallandetail.itemId
                    JOIN subcategory ON subcategory.subCategoryId = deliverychallandetail.subCategoryId
  	               WHERE masterDeliveryId = ".$fmRow['masterDeliveryId']."
  	               ORDER BY deliverychallanmaster.deliveryChallanMasterId";
    $selMstDtlRes = mysql_query($selMstDtl);
    $deliveryDetailCount = 0;
    while($mstDtlRow = mysql_fetch_array($selMstDtlRes))
    {
    	$deliveryDetailArray[$deliveryChallanCount][$deliveryDetailCount]['deliveryChallanDetailId']  = $mstDtlRow['deliveryChallanDetailId'];
    	$deliveryDetailArray[$deliveryChallanCount][$deliveryDetailCount]['masterDeliveryId']  = $fmRow['masterDeliveryId'];
    	if(isset($deliveryDetailArray[$deliveryChallanCount][$deliveryDetailCount-1]['masterDeliveryId']) && $deliveryDetailArray[$deliveryChallanCount][$deliveryDetailCount]['masterDeliveryId'] == $fmRow['masterDeliveryId'])
    	{
    		$deliveryDetailArray[$deliveryChallanCount][$deliveryDetailCount]['masterDeliveryId'] = "";
    		$deliveryDetailArray[$deliveryChallanCount][$deliveryDetailCount]['display'] = 0;
    	}
    	else
    	{
    		$deliveryDetailArray[$deliveryChallanCount][$deliveryDetailCount]['masterDeliveryId'] = $fmRow['masterDeliveryId'];
    		$deliveryDetailArray[$deliveryChallanCount][$deliveryDetailCount]['display'] = 1;
    	}
    	
    	$deliveryDetailArray[$deliveryChallanCount][$deliveryDetailCount]['deliveryChallanMasterId']  = $mstDtlRow['deliveryChallanMasterId'];
    	$deliveryDetailArray[$deliveryChallanCount][$deliveryDetailCount]['companyName']  = $mstDtlRow['companyName'];
    	$deliveryDetailArray[$deliveryChallanCount][$deliveryDetailCount]['srNo']         = $mstDtlRow['srNo'];
    	$deliveryDetailArray[$deliveryChallanCount][$deliveryDetailCount]['delivaryDate'] = $mstDtlRow['delivaryDate'];
    	$deliveryDetailArray[$deliveryChallanCount][$deliveryDetailCount]['challanType']  = $mstDtlRow['challanType'];
    	$deliveryDetailArray[$deliveryChallanCount][$deliveryDetailCount]['itemId']       = $mstDtlRow['itemId'];
    	$deliveryDetailArray[$deliveryChallanCount][$deliveryDetailCount]['subCategoryName'] = $mstDtlRow['subCategoryName'];
    	$deliveryDetailArray[$deliveryChallanCount][$deliveryDetailCount]['quantity']        = $mstDtlRow['quantity'];
	    if($mstDtlRow['discription'] != "")
	    {
	      $deliveryDetailArray[$deliveryChallanCount][$deliveryDetailCount]['itemName'] = $mstDtlRow['itemName']." # ".$mstDtlRow['discription'];
	    }                                                                               
	    else                                                                            
	    {                                                                               
	      $deliveryDetailArray[$deliveryChallanCount][$deliveryDetailCount]['itemName'] = $mstDtlRow['itemName'];
	    }
	    $deliveryDetailCount++;
    }
    $deliveryChallanCount++;
  }  
  
  
  
//  $selectDeliveryChallan = "SELECT deliverychallanmaster.deliveryChallanMasterId,deliverychallanmaster.address,deliverychallanmaster.challanType,
//                                   deliverychallanmaster.srNo,deliverychallanmaster.status,user.userId,user.userName,DATE_FORMAT(deliverychallanmaster.delivaryDate,'%d-%m-%Y') AS delivaryDate,
//                                   party.partyId,party.companyName AS partyCompany,supplier.supplierId,supplier.companyName AS suplierCompany
//                              FROM deliverychallanmaster
//                              LEFT JOIN user  ON user.userId   = deliverychallanmaster.userId
//                              LEFT JOIN supplier ON supplier.supplierId = deliverychallanmaster.supplierId
//                              LEFT JOIN party ON party.partyId    = deliverychallanmaster.partyId
//                             WHERE deliveryChallanMasterId =".$deliveryChallanMasterId;
//  $selectDeliveryResult = mysql_query($selectDeliveryChallan);
//  while($deliveryChallanRow = mysql_fetch_array($selectDeliveryResult))
//  {
//    $deliveryChallanArray[$deliveryChallanCount]['deliveryChallanMasterId']  = $deliveryChallanRow['deliveryChallanMasterId'];
//    if($deliveryChallanRow['partyCompany'] != "")
//      $deliveryChallanArray[$deliveryChallanCount]['companyName']            = $deliveryChallanRow['partyCompany'];
//    else
//      $deliveryChallanArray[$deliveryChallanCount]['companyName']            = $deliveryChallanRow['suplierCompany'];
//      
//    $deliveryChallanArray[$deliveryChallanCount]['srNo']                     = $deliveryChallanRow['srNo'];
//    $deliveryChallanArray[$deliveryChallanCount]['challanType']              = $deliveryChallanRow['challanType'];
//    $deliveryChallanArray[$deliveryChallanCount]['display']                  = 0;
//    $selectdeliverychallandetail = "SELECT deliverychallandetail.deliveryChallanMasterId,deliverychallandetail.deliveryChallanDetailId,deliverychallandetail.discription,
//                                           deliverychallandetail.itemId,deliverychallandetail.subCategoryId,deliverychallandetail.quantity,
//                                           deliverychallandetail.masterDeliveryId,item.itemId,item.itemName,subcategory.subCategoryId,subcategory.subCategoryName
//                                      FROM deliverychallandetail
//                                      JOIN item ON item.itemId = deliverychallandetail.itemId
//                                      JOIN subcategory ON subcategory.subCategoryId = deliverychallandetail.subCategoryId
//                                     WHERE deliverychallandetail.masterDeliveryId != 0
//                                     AND deliverychallandetail.deliveryChallanMasterId = ".$deliveryChallanRow['deliveryChallanMasterId']." ";  
//    $deliverychallandetailQuery = mysql_query($selectdeliverychallandetail);    
//    $deliveryDetailCount = 0;     
//    while($deliverychallandetailRow = mysql_fetch_array($deliverychallandetailQuery))
//    {
//    	$deliveryChallanArray[$deliveryChallanCount]['display'] = 1;
//	    $deliveryDetailArray[$deliveryChallanCount][$deliveryDetailCount]['deliveryChallanDetailId'] = $deliverychallandetailRow['deliveryChallanDetailId'];
//	    if($deliverychallandetailRow['discription'] != "")
//	    {
//	      $deliveryDetailArray[$deliveryChallanCount][$deliveryDetailCount]['itemName'] = $deliverychallandetailRow['itemName']." # ".$deliverychallandetailRow['discription'];
//	    }                                                                               
//	    else                                                                            
//	    {                                                                               
//	      $deliveryDetailArray[$deliveryChallanCount][$deliveryDetailCount]['itemName'] = $deliverychallandetailRow['itemName'];
//	    }
//	    $deliveryDetailArray[$deliveryChallanCount][$deliveryDetailCount]['subCategoryName']         = $deliverychallandetailRow['subCategoryName'];
//	    $deliveryDetailArray[$deliveryChallanCount][$deliveryDetailCount]['itemId']                  = $deliverychallandetailRow['itemId'];
//	    $deliveryDetailArray[$deliveryChallanCount][$deliveryDetailCount]['quantity']                = $deliverychallandetailRow['quantity'];
//	    $deliveryDetailArray[$deliveryChallanCount][$deliveryDetailCount]['rowCount']                = $deliveryDetailCount;
//	    $deliveryDetailCount++;
//    }
//    $deliveryChallanCount++;
//  }
  
  $selectMaxSr = "SELECT MAX(proformaMasterId) + 1 AS srNo
                    FROM proformamaster ";
  $selectMaxSrRes = mysql_query($selectMaxSr);
  if($srRow = mysql_fetch_array($selectMaxSrRes))
  {
  	$srNo   = $srRow['srNo'];
  }
  
  include("./bottom.php");
  $smarty->assign("srNo",$srNo);
  $smarty->assign("deliveryChallanArray",$deliveryChallanArray);
  $smarty->assign("deliveryDetailArray",$deliveryDetailArray);
  $smarty->assign("deliveryChallanMasterId",$deliveryChallanMasterId);
  $smarty->display("proforma.tpl");
}
?>